import { NavigateFunction } from "react-router/dist/lib/hooks";
import { NotificationInstance } from "antd/es/notification/interface";
import { MenuProps, notification } from "antd";
import { useNavigate } from "react-router";
import React, { useEffect } from "react";
import Constant from "@/config/constant";
import { To } from "react-router-dom";
import { RouteElement } from "@/config/route/route-types";
import { util } from "@/common/util";
import { LoaderRoute } from "@/config/route/loader-route";
import LoginUser from "@/config/user";

let HNavigate: NavigateFunction;
let HNotification: NotificationInstance;
let HRouteMedata = await LoaderRoute()

export function InitializeNavigate() {
    const [api, contextHolder] = notification.useNotification();
    let navigate = useNavigate()
    useEffect(() => {
        HNavigate = navigate
        HNotification = api
    }, [navigate, api])
    useEffect(() => {

        if (window.location.pathname !== "/login" && !hasIdentityUrl(window.location.pathname)) {
            util.toLogin()
        }
    }, [navigate])

    return <>{contextHolder}</>
}

export function hasEmpower(powerCode?: string): boolean {
    if (powerCode !== undefined && powerCode !== "") {
        return LoginUser.btnMapping.indexOf(powerCode) !== -1
    }
    return true;
}

export function hasIdentityUrl(toUrl?: To): boolean {
    // if (Constant.Identity && toUrl !== undefined) {
    //     let url: string;
    //     if (typeof toUrl === "string") {
    //         url = toUrl
    //     } else {
    //         url = toUrl.pathname!;
    //     }
    //     return HRouteMedata.mapping[url] !== undefined
    // }
    return true;
}

function getLayoutItem(element: RouteElement, setSelectKey: (key: string) => void): Required<MenuProps>['items'][number] {
    return {
        key: element.path,
        icon: util.LazyIcon(element.icon),
        children: element.children && element.children.length > 0 ? element.children.map(p => getLayoutItem(p, setSelectKey)) : undefined,
        label: <span>{element.menuName}</span>,
    };
}


export function getLayout(setSelectKey: (key: string) => void): Required<MenuProps>['items'][number][] {
    // 接口路由： LoginUser.menuMapping
    let items: Required<MenuProps>['items'][number][] = []
    LoginUser.menuMapping.forEach(p => {
        items.push(getLayoutItem(p, setSelectKey))
    })
    return items
}

export { HNotification, HRouteMedata, HNavigate }